//
//  AppDelegate.m
//  Alarm3DExperiments4
//
//  Created by 우성 김 on 12. 4. 5..
//  Copyright (c) 2012년 yy01ar@gmail.com. All rights reserved.
//

#import "AppDelegate.h"
//#import "HTTPRequest.h"
#import "HttpLogger.h"
#import "ViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSLog(@"application didFinishLaunchingWithOptions method called");
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    
    //timer = [NSTimer scheduledTimerWithTimeInterval:(60.0) target:self selector:@selector(targetMethod:) userInfo:nil repeats:YES];
//             scheduledTimerWithInterval: 10.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: NO];

    //[timer release];
    logger = [[HttpLogger alloc] init];
    
    return YES;
}


-(void)targetMethod:(NSTimer *)theTimer 
{
    NSLog(@"Timer called");
    
    NSString *stateString;
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateInactive) {
        stateString = @"Inactive State";
    } else if (state == UIApplicationStateBackground) {
        stateString = @"Background State";
    } else {
        stateString = @"Active State";
    }
    NSLog(@"State : %@\n----------------------------------------", stateString);
    
    [logger sendSimpleAsyncRequestWithTag:@"inactive_timerCall" andDescription:[NSString stringWithFormat:@"Timer was called.\nState : %@", stateString]];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    NSLog(@"applicationWillResignActive method called");
    
    NSString *stateString;
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateInactive) {
        stateString = @"Inactive State";
    } else if (state == UIApplicationStateBackground) {
        stateString = @"Background State";
    } else {
        stateString = @"Active State";
    }
    NSLog(@"State : %@\n----------------------------------------", stateString);
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    NSLog(@"applicationDidEnterBackground method called");
    
    NSString *stateString;
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateInactive) {
        stateString = @"Inactive State";
    } else if (state == UIApplicationStateBackground) {
        stateString = @"Background State";
    } else {
        stateString = @"Active State";
    }
    NSLog(@"State : %@\n----------------------------------------", stateString);
/*    
    NSString *stateString;
    UIApplicationState state = [application applicationState];
    if (state == UIApplicationStateInactive) {
        stateString = @"Sent to background by locking screen";
    } else if (state == UIApplicationStateBackground) {
        stateString = @"Sent to background by home button/switching to other app";
    } 
    NSLog(@"%@", stateString);
    
    [logger sendSimpleAsyncRequestWithTag:@"getAppState" andDescription:stateString];
    
    backgroundTask = [application beginBackgroundTaskWithExpirationHandler: ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTask != UIBackgroundTaskInvalid)
            {
                [application endBackgroundTask:backgroundTask];
                backgroundTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    
    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        // Do the work associated with the task.
        for(long i = 0 ; i < 400000000 ; i++)
        { 
            float remain = [application backgroundTimeRemaining];
            [logger sendSimpleAsyncRequestWithTag:@"background Remaining Time" andDescription:[NSString stringWithFormat:@"last remained: %f", remain]];
            
            NSString *stateString;
            UIApplicationState state = [application applicationState];
            if (state == UIApplicationStateInactive) {
                stateString = @"Sent to background by locking screen";
            } else if (state == UIApplicationStateBackground) {
                stateString = @"Sent to background by home button/switching to other app";
            } 
            [logger sendSimpleAsyncRequestWithTag:@"getAppState" andDescription:stateString];
            
            [NSThread sleepForTimeInterval:60];
            
        }
        // Synchronize the cleanup call on the main thread in case
        // the expiration handler is fired at the same time.
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (backgroundTask != UIBackgroundTaskInvalid) {
                // 작업
                
                // 남은 시간
                //NSLog(@"%f", [application backgroundTimeRemaining]);
                
                [application endBackgroundTask:backgroundTask];
                backgroundTask = UIBackgroundTaskInvalid;
            }
        });
    });
*/
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //[receiveData appendData:data];
    NSLog(@"%@", data);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Connection Finished");
    
    NSString *stateString;
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateInactive) {
        stateString = @"Inactive State";
    } else if (state == UIApplicationStateBackground) {
        stateString = @"Background State";
    } else {
        stateString = @"Active State";
    }
    NSLog(@"State : %@\n----------------------------------------", stateString);
}


- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSLog(@"applicationWillEnterForeground method called");
    
    NSString *stateString;
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateInactive) {
        stateString = @"Inactive State";
    } else if (state == UIApplicationStateBackground) {
        stateString = @"Background State";
    } else {
        stateString = @"Active State";
    }
    NSLog(@"State : %@\n----------------------------------------", stateString);
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    NSLog(@"applicationDidBecomeActive method called");
    
    NSString *stateString;
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateInactive) {
        stateString = @"Inactive State";
    } else if (state == UIApplicationStateBackground) {
        stateString = @"Background State";
    } else {
        stateString = @"Active State";
    }
    NSLog(@"State : %@\n----------------------------------------", stateString);
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSLog(@"applicationWillTerminate method called");
}

// methods related location
-(void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
{

}

-(void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
{
    
}

@end
